import logging
import os
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import logging
from contextlib import asynccontextmanager

import fastapi_cdn_host

from backend.database.session import init_db, close_db
from backend.api import api_zt_stocks, api_kline
from backend.config import settings
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# lifespan事件处理器
@asynccontextmanager
async def lifespan(app: FastAPI):
    # 应用启动时执行
    logger.info("正在初始化数据库...")
    await init_db()
    logger.info("数据库初始化完成")
    
    yield
    
    # 应用关闭时执行
    logger.info("正在关闭数据库连接...")
    await close_db()
    logger.info("数据库连接已关闭")

# 创建FastAPI应用实例
app = FastAPI(
    title=settings.PROJECT_NAME,
    description=settings.PROJECT_DESCRIPTION,
    version=settings.PROJECT_VERSION,
    lifespan=lifespan
)


fastapi_cdn_host.patch_docs(app)


# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含路由
app.include_router(api_zt_stocks.router)
app.include_router(api_kline.router)

# 根路径
@app.get("/")
async def root():
    return {"message": "欢迎使用个人股票量化分析系统"}

# 健康检查端点
@app.get("/health")
async def health_check():
    return {"status": "healthy"}


if __name__ == "__main__":
    import uvicorn

    # 从环境变量读取host和port配置，默认值为0.0.0.0:8000（适用于外部访问）
    host = os.getenv("UVICORN_HOST", "0.0.0.0")
    port = int(os.getenv("UVICORN_PORT", 8000))
    reload = os.getenv("UVICORN_RELOAD", "True").lower() == "true"
    
    logger.info(f"Starting server on {host}:{port}")
    uvicorn.run("main:app", host=host, port=port, reload=reload)

